package cn.com.taiji.oospub.wechat.controller.servlet;

import cn.com.taiji.oospub.wechat.common.Finals;
import cn.com.taiji.oospub.wechat.common.ObjectToXML;
import cn.com.taiji.oospub.wechat.common.OrderSend;
import cn.com.taiji.oospub.wechat.common.util.HttpUtil;
import cn.com.taiji.oospub.wechat.common.wxpay.pay.XMLParser;
import cn.com.taiji.oospub.wechat.entity.CoursesOrders;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.oospub.wechat.entity.MemberStoreOrder;
import cn.com.taiji.oospub.wechat.service.IAccesstokensaveService;
import cn.com.taiji.oospub.wechat.service.ICoursesService;
import cn.com.taiji.oospub.wechat.service.IMemberBaseInfoService;
import cn.com.taiji.oospub.wechat.service.IMemberStoreOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import static cn.com.taiji.oospub.wechat.common.Finals.PROPERTIES_PATH;

@WebServlet("/weixin/notityStore")
public class WeiXinNotifyStore extends HttpServlet {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private IMemberBaseInfoService memberBaseInfoManager;
    private static InputStream kongxc_posPay_Stream;
    private Properties props = new Properties();
    private static String posPay_url;
    private IMemberStoreOrderService memberStoreOrderManager;
    private IAccesstokensaveService accesstokensaveService;
    private OrderSend orderSend;
    Map resCodeMap = new HashMap<String, String>();
    public String PROPASS;
    public String PROJECT_CODE;
    public String CUS_NAME;

    @Override
    public void init() throws ServletException {

        super.init();
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        memberBaseInfoManager = wac.getBean(IMemberBaseInfoService.class);
        memberStoreOrderManager = wac.getBean(IMemberStoreOrderService.class);
        accesstokensaveService = wac.getBean(IAccesstokensaveService.class);
        orderSend = wac.getBean(OrderSend.class);
        try {
            kongxc_posPay_Stream = wac.getResource(PROPERTIES_PATH).getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ICoursesService coursesManager = wac.getBean(ICoursesService.class);
        resCodeMap.put("0000", "成功");
        resCodeMap.put("9999", "失败");
        //------头结点的错误信息开始-----
        resCodeMap.put("0001", "接收的xml格式错误");
        resCodeMap.put("0002", "请求没有ARAMARK_REQUEST节点");
        resCodeMap.put("0003", "请求没有HEAD节点");
        resCodeMap.put("0004", "接收的xml格式无响应码");
        resCodeMap.put("0005", "接收的xml格式无内容");
        resCodeMap.put("0006", "接收的xml格式无描述");
        resCodeMap.put("0009", "接收的xml格式无孩子");
        resCodeMap.put("0015", "接收的xml没有账户编号");
        resCodeMap.put("0016", "接收的xml没有充值金额");
        resCodeMap.put("kongxc_032", "POS没有该账号");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), StandardCharsets.UTF_8));
        String line = "";
        StringBuffer buffer = new StringBuffer(1024);
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        String reXml = URLDecoder.decode(buffer.toString(), "utf-8");
        try {
            Map<String, Object> map = XMLParser.getMapFromXML(reXml);
            String return_code = (String) map.get("return_code");
            if ("SUCCESS".equalsIgnoreCase(return_code)) {
                String out_trade_no = (String) map.get("out_trade_no");
                QueryWrapper<MemberStoreOrder> memberStoreWrapper = new QueryWrapper<>();
                memberStoreWrapper.eq("FLOW_NO", out_trade_no);
                memberStoreWrapper.eq("UPDATE_OUT", "0");
//                memberStoreWrapper.eq("IS_PAY", "0");
                MemberStoreOrder memberStoreOrder = memberStoreOrderManager.getOne(memberStoreWrapper, false);
                memberStoreOrder.setIsPay("1");
//                memberStoreOrderManager.updateById(memberStoreOrder);
                MemberBaseInfo member = memberBaseInfoManager.getById(memberStoreOrder.getCustomerId());
                //订单详情推送
                //推送订单到pos
                String weChatCode = (String) map.get("out_trade_no");

                props.load(kongxc_posPay_Stream);
                posPay_url = props.getProperty("kongxc_pos_http_server_url");
                PROPASS = props.getProperty("PROPASS");
                CUS_NAME = props.getProperty("CUS_NAME");
                HttpUtil send = new HttpUtil(posPay_url);
                ObjectToXML toXml = new ObjectToXML(resCodeMap);
                String accountXml = toXml.requestRecharge(PROPASS, CUS_NAME, member.getSchool().getCode(), UUID.randomUUID().toString().replace("-", ""),
                        member.getIdNumber(), member.getPasswd(), member.getEmail(), "1", "微信储值", Double.parseDouble(memberStoreOrder.getActualAmount().toString()), weChatCode, Finals.pageSize, Finals.pageIndex);
                System.out.println("Strore___________________" + accountXml);
                String responseTradeXml = null;
                responseTradeXml = send.sendToBoss(accountXml);
                Map<String, String> responseAccount = toXml.resResXmlAccCharge(responseTradeXml);
                if ("0000".equals(responseAccount.get("resCode"))) {
                    memberStoreOrder.setUpdateOut("1");
                    CoursesOrders coursesOrders = new CoursesOrders();
                    coursesOrders.setOrderCode(memberStoreOrder.getFlowNo());
                    coursesOrders.setAmount(memberStoreOrder.getActualAmount());
                    coursesOrders.setAfterAmount(memberStoreOrder.getAfterAmount());
                    String accessToken = accesstokensaveService.query().one().getAccessToken();
                    orderSend.chuzhiMethod(accessToken, member, coursesOrders);
                    memberStoreOrderManager.updateById(memberStoreOrder);
                    resp.getWriter().print("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
                }
            }
        } catch (SAXException | ParserConfigurationException ex) {
            ex.printStackTrace();
        } catch (Exception ignored) {
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }

}